<?php

namespace App\Api;


use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\House;
use Illuminate\Http\Request;
use App\Http\Resources\HouseResource;
use Illuminate\Support\Facades\DB;
use PermissionService;

class HouseController extends Controller
{


    public function index(Article $article)
    {
        $this->authorize('viewAny', House::class);

        $houses = HouseResource::collection($article->houses);
        return $houses;
    }


    public function store(Request $request, Article $article, House $house)
    {
        $this->authorize('create', House::class);


        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $house = $article->houses()->create($request->input());
        $house->extra = ['price' => $request->price, 'time' => $request->time];
        $house->save();
        return $this->message('发表成功', $house->toArray());
    }

    public function show(Article $article, House $house)
    {
        $this->authorize('view', $house);

        return new HouseResource($house);
    }


    public function update(Request $request, Article $article, House $house)
    {
        $this->authorize('update', $house);

        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $house->update($request->input());
        $house->extra = ['price' => $request->price, 'time' => $request->time];
        $house->save();
        return $this->message('修改成功', $house->toArray());
    }


    public function destroy(Article $article, House $house)
    {
        $this->authorize('delete', $house);

        $house->delete();
        return $this->message('删除成功');
    }

    /**
     * 前台首页展示
     * @return House[]|\Illuminate\Database\Eloquent\Collection
     */
    public function houseList()
    {
        /**
         * 推荐信息前10，按时间最近展示
         */
        return House::where('recommend', 1)->orderBy('id', 'desc')->take(10)->get();
    }
}
